package com.cy.controller;

import com.cy.mapper.ContentMapper;
import com.cy.pojo.dto.ContentDTO;
import com.cy.pojo.po.Content;
import com.cy.pojo.vo.ContentVO;
import com.cy.response.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@Api(tags = "01. 内容管理模块")
public class ContentController {
    @Autowired
    private ContentMapper contentMapper;

    @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
    @ApiOperation("查询所有内容")
    public JsonResult selectAll() {
        log.debug("开始处理【查询内容列表】的请求，无参数");
        List<ContentVO> contentVOS = contentMapper.selectAll();
        contentVOS.forEach(System.out::println);
        return JsonResult.ok(contentVOS);
    }

    /*
     * 根据Id删除内容
     * */
    @RequestMapping(value = "/{id:[0-9]+}/delete", method = RequestMethod.POST)
    @ApiOperation("根据Id删除内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "内容Id", required = true, dataType = "long")
    })
    public JsonResult<Void> delete(@PathVariable Long id) {
        log.debug("开始处理【根据ID删除内容】的请求，参数：{}", id);
        ContentVO contentById = contentMapper.getContentById(id);
        log.debug("根据ID={}检查内容数据是否存在，查询结果：{}", id, contentById);
        // 判断查询结果是否为null
        if (contentById == null) {
            String message = "根据Id删除内容失败，尝试删除的数据不存在！";
            log.warn(message);
            return JsonResult.fail(message);
        } else {
            contentMapper.delete(id);
            return JsonResult.ok();
        }
    }

    /*
     * 新增内容
     * */

    @PostMapping("/addcontent")
    @ApiOperation("添加相册")
    public JsonResult<Void> addNew(ContentDTO contentDTO) {
        log.debug("开始处理【添加相册】的请求，参数：{}", contentDTO);
        contentMapper.add(contentDTO);
        return JsonResult.ok();
    }


    /*
     * 修改内容
     * */
    @PostMapping("/{id:[0-9]+}/update")
    @ApiOperation("修改内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "内容ID", required = true, dataType = "long")
    })
    public JsonResult<Void> updateContentById(@PathVariable Long id,
                                              ContentDTO contentDTO) {
        log.debug("开始处理【修改相册详情】的请求，ID：{}，新数据：{}", id, contentDTO);

        Content content = new Content();
        BeanUtils.copyProperties(contentDTO, content);
        content.setId(id);

        contentMapper.updateContentById(content);


        return JsonResult.ok();
    }

}
